const app = getApp()
const {
  request
} = require('../../utils/request.js');
const api = require('../../utils/api.js');
const rewardAd = require('../../utils/rewardAd.js');

Page({
  data: {
    searchValue: '',
    showClearIcon: false,
    isLoading: false,
    showCamera: false,
    cameraContext: null,
    cameraDevice: 'back',
    cameraFlash: 'off',
    isInputFocused: false,
    takingPhoto: false,
    showAgreement: false,
    isAgreed: false,
    showGuideAddTips: false,
    showShareGuide: false,
    currentSwiperIndex: 0, // 当前轮播图索引
    // 轮播图数据
    bannerList: [],
    // 会员信息
    creditCount: 15,
    inviteCount: 3,
    // 导航栏和状态栏高度
    // 公告文本
    noticeText: '使用须知：本软件请勿用于考试使用.仅供用户学习使用.模拟考试学习使用.禁止正式考试使用.否则后果自负，与本平台软件无关。',
    remainingCredits: 1,
    audioPlaying: false,
    isPlaying: false,
    audioContext: null,
    userInfo: null,
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    // 当前选中的底部导航
    currentTab: 'home',
    // 城市和天气信息
    city: '官宇',
    temperature: '21°C',
    weatherType: '多云',
    // 未读消息数
    unreadCount: 1,
    // 用户信息
    userInfo: {
      creditCount: 10,
      totalCredits: 20
    },
    searchHeight: 0,
    headerHeight: 0,
    current_id: 0,

    popupVisible: false, // 控制弹窗的显示与隐藏
    imageUrl: app.globalData.service_icon, // 图片链接
    popupText: '长按二维码,咨询客服',
    showPopup: false,
    popup: {},
    showUserInfoPopup: false, // 控制用户信息弹窗显示
    car_function: {},
    showDDPopup: false,
    ddImageUrl: 'https://img0.baidu.com/it/u=922451792,713741033&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500', // DD代驾图片URL
    showVideoAd: false,
    topBgColor: app.globalData.topBgColor,



    displayStyle: '',
    navBarHeight: 0, // 导航栏高度
    statusBarHeight: 0, // 状态栏高度
    totalHeight: 0, // 总高度
    MenuButton: {},
    swiperCurrent: 0,

    show_add_mp: true,
    add_mp_right: 0,
  },
  onLoad: function (options) {

    // 获取系统信息和胶囊按钮信息
    try {
      const rect = wx.getMenuButtonBoundingClientRect()
      wx.getSystemInfo({
        success: (res) => {
          const isAndroid = res.platform === 'android'
          const isDevtools = res.platform === 'devtools'

          // 计算导航栏高度
          const statusBarHeight = res.statusBarHeight;
          const navBarHeight = isAndroid ? 48 : 44;
          const totalHeight = statusBarHeight + navBarHeight;
          this.setData({
            innerPaddingRight: `padding-right: ${res.windowWidth - rect.left}px`,
            leftWidth: `width: ${res.windowWidth - rect.left}px`,
            statusBarHeight,
            navBarHeight,
            totalHeight,
            MenuButton: rect
          })
        }
      })

      // 获取的数值单位是px
      const windowInfo = wx.getWindowInfo();
      const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
      let statusBarHeight = windowInfo.statusBarHeight;
      let navBarHeight =
        menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) * 2;
      let safeHeight = windowInfo.safeArea.height;
      let bottomSafeHeight =
        windowInfo.screenHeight - windowInfo.safeArea.height - statusBarHeight;
      this.setData({
        statusBarHeight,
        navBarHeight,
        safeHeight,
        bottomSafeHeight,
      });
    } catch (e) {
      // 设置默认值
      this.setData({
        statusBarHeight: 20,
        navBarHeight: 44,
        menuButtonHeight: 32,
        headerHeight: 120,
        navPlaceholderHeight: 64 // 默认状态栏(20) + 导航栏(44)
      });
    }
    // 其他初始化逻辑
    const hasAgreed = wx.getStorageSync('hasAgreed');
    if (!hasAgreed) {
      this.setData({
        showAgreement: true
      });
    }
    // 获取用户数据
    if (app.globalData.hasLogin && app.globalData.user_id) {
      this.getUserData();
      this.checkUserInfo(); // 检查用户信息是否完整
    } else {
      app.globalData.userLoginReadyCallback = userInfo => {
        this.getUserData();
        this.checkUserInfo(); // 检查用户信息是否完整
      };
    }
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      });
    }
    // 获取公告数据
    this.fetchNotices();
    this.get_popup_active()
    this.getUserInfo();
    this.checkShowAddMiniprogramTips();
    this.checkShowShareGuide();
    this.getMemberInfo();
    this.getWeatherInfo();
    this.getNoticeData();
    this.check_add_mp()
    // 在onLoad中调用
    if (!wx.getStorageSync('token')) {
      app.waitForLogin(() => {
        this.executeConfigRequests();
      });
    } else {
      this.executeConfigRequests();
    }

  },

  executeConfigRequests() {
    this.get_function();
    this.initRewardAd();
    this.get_banners();
  },


  check_add_mp() {
    const addMp = wx.getStorageSync('addMp')

    if (addMp) {
      this.setData({
        show_add_mp: false
      })
    } else {

      const {
        height,
        width,
        top,
        bottom,
        right,
        left
      } = this.data.MenuButton
      // bottom: 83
      // height: 32
      // left: 296
      // right: 383
      // top: 51
      // width: 87
      console.log(wx.getSystemInfoSync().windowWidth);
      const syswidth = wx.getSystemInfoSync().windowWidth
      let add_mp_right = (syswidth - right + (width / 2))
      this.setData({
        show_add_mp: true,
        add_mp_right
      })
    }

  },
  initRewardAd() {
    app.getConfig('videoAd', res => {
      if (res.is_public) {
        this.setData({
          showVideoAd: true
        })
        rewardAd.initRewardAd(res.value, (isFinished) => {
          if (isFinished) {
            this.unlockContent();
          } else {
            wx.showToast({
              title: '请完整观看视频才能领取奖励',
              icon: 'none'
            });
          }
        });
      }
    })


  },
  // 防止滚动穿透
  preventTouchMove() {
    return false;
  },
  // 处理复选框变化
  handleCheckboxChange(e) {
    this.setData({
      isAgreed: e.detail.value.length > 0
    });
  },
  // 处理不同意
  handleDisagree() {
    wx.showModal({
      title: '提示',
      content: '您需要同意用户协议才能使用小程序',
      showCancel: false,
      success: () => {
        wx.exitMiniProgram();
      }
    });
  },

  get_function() {
    app.getConfig('car_function', res => {
      if (res.is_public) {
        if (typeof res.value === "string") {
          res.value = JSON.parse(res.value)
        }
        this.setData({
          car_function: res.value
        })
      }
    })
  },

  // 分享给朋友
  onShareAppMessage: async function () {
    let title = '学法减分+全题型覆盖！一次通关必备！';
    let imageUrl = '/image/0404.png';
    return {
      title: title,
      path: '/pages/index/index?sharerId=' + wx.getStorageSync('userId'),
      imageUrl: imageUrl
    };
  },
  // 分享到朋友圈（仅支持基础库 2.11.3 以上）
  onShareTimeline: function () {
    return {
      title: '学法减分题库 - 你的学习助手',
      query: 'from=timeline', // 分享参数
      imageUrl: ''
    }
  },
  onShareTap: function () {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },
  // 处理同意
  handleAgree() {
    if (!this.data.isAgreed) {
      wx.showToast({
        title: '请先阅读并同意用户协议',
        icon: 'none'
      });
      return;
    }

    // 保存同意状态
    wx.setStorageSync('hasAgreed', true);

    // 关闭弹窗
    this.setData({
      showAgreement: false
    });

    // 可以在这里进行其他初始化操作
  },
  onShow: function () {
    // 设置tabbar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0 // 首页对应索引0
      });
    }
    // 刷新用户数据
    this.getUserData();
    // 启动公告滚动

    // 每次页面显示时检查用户信息
    if (app.globalData.hasLogin && app.globalData.userInfo) {
      this.checkUserInfo();
    }



  },
  toExam: function () {
    wx.navigateTo({
      url: '/pages/exam/exam',
    })
  },
  onHide: function () {},
  onUnload: function () {
    // 页面卸载时销毁音频上下文
    if (this.audioContext) {
      this.audioContext.destroy();
    }

    // 停止走马灯
    if (this.data.marqueeInterval) {
      clearInterval(this.data.marqueeInterval);
    }
  },
  // 获取公告数据
  fetchNotices: function () {
    request(api.notices, 'GET')
      .then(res => {
        // 格式化公告文本，添加"使用须知："前缀，保持与拍照页面一致
        let notice = res.data.list[0].content || "欢迎使用学法减分题库小程序，助您轻松搜题！";
        if (!notice.startsWith('使用须知：')) {
          notice = '使用须知：' + notice;
        }

        this.setData({
          noticeText: notice
        });
      })
      .catch(err => {
        console.error('获取失败', err);
        // 设置默认公告
        this.setData({
          noticeText: '使用须知：本软件请勿用于考试使用.仅供用户学习使用.模拟考试学习使用.禁止正式考试使用.'
        });
      });
  },
  // 获取轮播图数据
  get_banners: function () {
    request(api.banners, 'GET')
      .then(res => {
        this.preloadBannerColors(res.data.list);
      })
      .catch(err => {
        console.log('获取失败', err);
      });
  },
  get_popup_active() {
    const today = this.getTodayDate();
    const noAdToday = wx.getStorageSync('noAdToday');

    if (noAdToday === today) {
      return;
    }
    request(api.popupActive, 'GET')
      .then(res => {
        console.log(res);
        if (res.data?.enabled) {
          this.setData({
            popup: res.data,
            showPopup: true
          })
        }
      })
      .catch(err => {
        console.error('获取失败', err);
      });
  },

  getTodayDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = `${date.getMonth() + 1}`.padStart(2, '0');
    const day = `${date.getDate()}`.padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  onPopupClosed() {
    const today = this.getTodayDate(); // 如 2025-05-19
    wx.setStorageSync('noAdToday', today);
    this.setData({
      showPopup: false
    });
  },
  // 执行搜索
  doSearch: function () {
    const keyword = this.data.searchValue.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      });
      return;
    }

    // 保存到搜索历史
    app.saveSearchHistory(keyword);

    // 跳转到结果页
    wx.navigateTo({
      url: `/pages/result/result?keyword=${encodeURIComponent(keyword)}`
    });
  },

  // 获取用户剩余次数
  getUserCredits: function () {
    // 模拟从服务器获取数据
    this.setData({
      remainingCredits: 1
    });
  },
  // 绑定推荐关系
  bindShare(userId, sharerId) {
    if (!sharerId || !userId || userId === sharerId) {
      console.log('参数不合法，跳过绑定');
      return;
    }
    request(api.shareBind, 'POST', {
        userId: userId,
        sharerId: sharerId
      })
      .then(res => {
        console.log('绑定成功：', res.data.msg);
      })
      .catch(err => {
        console.log('绑定失败：', err.data.msg);
      });
  },
  getShareCount(sharerId) {
    if (!sharerId) return;
    request(api.shareCount + '?sharerId=' + sharerId, 'GET')
      .then(res => {
        const inviteCount = res.count;
        this.setData({
          inviteCount: inviteCount,
        });
      })
      .catch(err => {
        console.error('获取搜索次数失败', err);
      });
  },



  navigateToCamera: function () {
    wx.switchTab({
      url: '/pages/photo/photo',
    })
  },
  // 获取用户数据
  getUserData: function () {
    // 检查用户ID是否存在
    if (!app.globalData.user_id) {
      return;
    }
    // 从服务器获取用户数据
    app.getUserProfile(data => {
      if (data) {
        const userInfo = data.userInfo;
        this.setData({
          creditCount: userInfo.usage_count,
        });

        this.getShareCount(userInfo.user_id)
      } else {
        // 获取失败
        console.log('获取用户信息失败');
      }
    });
  },
  // 显示使用指南
  showGuide: function () {
    wx.navigateTo({
      url: '/pages/index/article/index'
    });
  },
  // 联系客服
  contactService: function () {

  },
  // 关注公众号
  followOfficial: function () {
    wx.navigateTo({
      url: '/pages/official/official'
    });
  },
  // 前往模拟考试
  startExam: function () {
    wx.navigateTo({
      url: '/pages/exam/exam'
    });
  },
  // 分享给好友
  shareWithFriends: function (e) {
    // 阻止事件冒泡
    e.stopPropagation();

    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },
  // 领取奖励
  claimReward: function (e) {
    // 阻止事件冒泡
    e.stopPropagation();

    wx.showLoading({
      title: '领取中...',
    });


  },
  getUserInfo() {
    const app = getApp()
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      this.getUserProfile()
    }
  },
  startArticle: function () {
    wx.navigateTo({
      url: '/pages/index/article/index',
    })
  },
  getUserProfile() {
    const app = getApp()
    app.getUserProfile((userData) => {
      if (userData) {
        this.setData({
          creditCount: userData.credit_count || 0,
        })
      }
    })
  },
  // 检查是否显示添加小程序提示
  checkShowAddMiniprogramTips: function () {
    const hasShownAddTips = wx.getStorageSync('hasShownAddTips');
    // 如果之前没有显示过，显示引导提示
    if (!hasShownAddTips) {
      // 延迟3秒后显示
      setTimeout(() => {
        this.setData({
          showGuideAddTips: true
        });
      }, 3000);
    }
  },

  // 关闭添加小程序提示
  closeGuideAddTips: function () {
    this.setData({
      showGuideAddTips: false
    });
    wx.setStorageSync('hasShownAddTips', true);
  },

  // 显示添加小程序到"我的小程序"的引导
  showAddMiniProgramTips: function () {
    this.setData({
      showGuideAddTips: true
    });
  },

  // 检查是否显示分享引导
  checkShowShareGuide: function () {
    const hasShownShareGuide = wx.getStorageSync('hasShownShareGuide');
    // 每天只显示一次
    const lastShownDate = wx.getStorageSync('lastShownShareGuideDate');
    const today = new Date().toDateString();

    if (!hasShownShareGuide || lastShownDate !== today) {
      // 延迟5秒后显示
      setTimeout(() => {
        this.setData({
          showShareGuide: true
        });
        wx.setStorageSync('lastShownShareGuideDate', today);
      }, 5000);
    }
  },

  preloadBannerColors(images) {
    images.forEach((item, index) => {
      if (index == 0 && item.hex) {
        this.setData({
          topBgColor: item.hex
        })
      }
      if (!item.hex) {
        console.log("调用颜色");
        // 异步获取主色调
        this.getImageMainColor(item.imageUrl, (hex) => {
          item.hex = hex;
          console.log(hex);
          // 调用接口更新 hex 值
          request(api.banners + "/" + item.id, 'PUT', item, {
            header: {
              'Content-Type': 'application/json'
            }
          })
        });
      }
    });
    this.setData({
      bannerList: images
    });
  },
  onSwiperChange: function (e) {
    const img = this.data.bannerList[e.detail.current];
    this.setData({
      current_id: e.detail.current,
      topBgColor: img.hex
    })
  },
  getImageMainColor(url, callback) {
    wx.downloadFile({
      url: url,
      success: res => {
        if (res.statusCode === 200) {
          console.log("获取hex");
          this.drawImageToCanvas(res.tempFilePath, callback);
        } else {
          console.log('downloadFile状态码错误', res.statusCode);
        }
      },
      fail: err => {
        // console.error('downloadFile失败', err);
      }
    });
  },

  drawImageToCanvas(path, callback) {

    const ctx = wx.createCanvasContext('colorCanvas', this);
    ctx.clearRect(0, 0, 10, 10);
    ctx.drawImage(path, 0, 0, 10, 10);
    ctx.draw(true, () => {
      wx.canvasGetImageData({
        canvasId: 'colorCanvas',
        x: 0,
        y: 0,
        width: 1,
        height: 1,
        success: res => {
          const rgb = this.calculateAverageRGB(res.data);
          const hex = this.rgbToHex(rgb.r, rgb.g, rgb.b);
          callback(hex); // 通过回调返回颜色
        },
        fail: err => {
          console.error('获取 canvas 像素失败', err);
        }
      }, this);
    });
  },

  calculateAverageRGB(data) {
    let r = 0,
      g = 0,
      b = 0;
    const len = data.length / 4;
    for (let i = 0; i < data.length; i += 4) {
      r += data[i];
      g += data[i + 1];
      b += data[i + 2];
    }
    return {
      r: Math.round(r / len),
      g: Math.round(g / len),
      b: Math.round(b / len)
    };
  },

  rgbToHex(r, g, b) {
    return '#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join('');
  },


  // 关闭分享引导
  closeShareGuide: function () {
    this.setData({
      showShareGuide: false
    });
    wx.setStorageSync('hasShownShareGuide', true);
  },
  // 轮播图切换事件
  swiperChange: function (e) {
    this.setData({
      currentSwiperIndex: e.detail.current
    });
  },
  // 获取会员信息
  getMemberInfo() {
    // TODO: 调用接口获取会员信息
  },
  // 处理扫码
  handleScan: function () {
    wx.scanCode({
      success: (res) => {
        console.log('扫码结果:', res);
        // 处理扫码结果
        if (res.result) {
          wx.showModal({
            title: '扫码成功',
            content: '扫码结果：' + res.result,
            showCancel: false
          });
        }
      },
      fail: (err) => {
        console.error('扫码失败:', err);
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        });
      }
    });
  },
  // 处理消息
  handleMessage: function () {
    wx.navigateTo({
      url: '/pages/message/message'
    });
  },
  // 处理搜索
  handleSearch: function () {
    wx.navigateTo({
      url: '/pages/search/search'
    });
  },
  // 处理轮播图点击
  handleBannerClick: function (e) {
    const id = e.currentTarget.dataset.id;
    console.log('点击了轮播图:', id);

    // 根据ID跳转到不同页面
    wx.navigateTo({
      url: '/pages/banner/detail?id=' + id
    });
  },
  // 处理历史记录
  handleHistory: function () {
    wx.navigateTo({
      url: '/pages/history/history'
    });
  },
  // 处理会员中心更多
  handleMemberMore() {
    // TODO: 跳转到会员中心页面
  },
  // 切换底部导航
  switchTab: function (e) {
    const index = parseInt(e.currentTarget.dataset.index);
    let tabName = 'home';

    // 根据索引设置对应的tab名称
    if (index === 0) {
      tabName = 'home';
    } else if (index === 1) {
      tabName = 'camera';
    } else if (index === 2) {
      tabName = 'user';
    }

    // 设置当前tab
    this.setData({
      currentTab: tabName
    });

    // 根据tab跳转到不同页面
    if (tabName === 'camera') {
      wx.navigateTo({
        url: '/pages/photo/photo'
      });
    } else if (tabName === 'user') {
      wx.navigateTo({
        url: '/pages/profile/profile'
      });
    }
  },
  // 开始使用教程
  startArticle() {
    wx.navigateTo({
      url: '/pages/guide/index'
    })
  },
  // 开始模拟考试
  startExam() {
    wx.navigateTo({
      url: '/pages/exam/index'
    })
  },
  // 获取位置和天气信息
  getLocationWeather: function () {
    const that = this;

    // 先获取用户位置
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        const latitude = res.latitude;
        const longitude = res.longitude;

        // 通过位置获取城市
        that.getCityName(latitude, longitude);

        // 通过位置获取天气
        that.getWeather(latitude, longitude);
      },
      fail: function () {
        // 获取位置失败，使用默认值
        that.setData({
          city: '杭州',
          temperature: '21°C',
          weatherType: '多云'
        });

        // 提示用户
        wx.showToast({
          title: '无法获取位置，使用默认天气',
          icon: 'none'
        });
      }
    });
  },

  // 获取城市名称
  getCityName: function (latitude, longitude) {
    const that = this;
    wx.request({
      url: 'https://api.map.baidu.com/reverse_geocoding/v3',
      data: {
        ak: '您的百度地图API密钥', // 需要替换为实际的百度地图API密钥
        output: 'json',
        coordtype: 'wgs84ll',
        location: latitude + ',' + longitude
      },
      success: function (res) {
        if (res.data && res.data.result && res.data.result.addressComponent) {
          const city = res.data.result.addressComponent.city || '杭州';
          that.setData({
            city: city.replace('市', '')
          });
        }
      },
      fail: function () {
        that.setData({
          city: '杭州'
        });
      }
    });
  },

  // 获取天气信息
  getWeather: function (latitude, longitude) {
    const that = this;
    wx.request({
      url: 'https://devapi.qweather.com/v7/weather/now',
      data: {
        key: '您的和风天气API密钥', // 需要替换为实际的和风天气API密钥
        location: longitude + ',' + latitude
      },
      success: function (res) {
        if (res.data && res.data.now) {
          const weatherData = res.data.now;
          that.setData({
            temperature: weatherData.temp + '°C',
            weatherType: weatherData.text
          });
        }
      },
      fail: function () {
        that.setData({
          temperature: '21°C',
          weatherType: '多云'
        });
      }
    });
  },

  // 获取系统信息
  getSystemInfo: function () {
    const that = this;
    try {
      // 获取系统信息
      const systemInfo = wx.getSystemInfoSync();

      // 获取胶囊按钮位置信息
      const menuButtonInfo = wx.getMenuButtonBoundingClientRect();

      // 计算导航栏高度 = 胶囊按钮高度 + (胶囊按钮top - 状态栏高度) * 2
      const navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - systemInfo.statusBarHeight) * 2;

      // 计算导航栏内容区域的内边距，使其适配胶囊按钮
      const rightPadding = systemInfo.windowWidth - menuButtonInfo.left + 5;

      that.setData({
        statusBarHeight: systemInfo.statusBarHeight,
        navBarHeight: navBarHeight,
        menuButtonHeight: menuButtonInfo.height,
        menuButtonTop: menuButtonInfo.top,
        menuButtonInfo: menuButtonInfo,
        menuPadding: (menuButtonInfo.top - systemInfo.statusBarHeight),
        menuRight: rightPadding
      });

      console.log('状态栏高度:', systemInfo.statusBarHeight);
      console.log('导航栏高度:', navBarHeight);
      console.log('胶囊按钮高度:', menuButtonInfo.height);
      console.log('胶囊按钮top:', menuButtonInfo.top);
      console.log('内边距:', (menuButtonInfo.top - systemInfo.statusBarHeight));
    } catch (e) {
      console.error('获取系统信息出错:', e);

      // 如果出错，使用默认值
      that.setData({
        statusBarHeight: 20,
        navBarHeight: 44
      });
    }
  },

  // 获取天气信息
  getWeatherInfo: function () {
    // 实际开发中应该调用天气API
    // 这里使用模拟数据
    const weatherData = {
      temp: '26°',
      condition: '晴',
      icon: 'sunny'
    };

    this.setData({
      weatherInfo: weatherData
    });
  },

  // 处理客服服务
  handleCustomService: function () {
    wx.showActionSheet({
      itemList: ['在线客服', '电话咨询', '问题反馈'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 在线客服
          wx.showToast({
            title: '即将上线，敬请期待',
            icon: 'none'
          });
        } else if (res.tapIndex === 1) {
          // 电话咨询
          wx.makePhoneCall({
            phoneNumber: '400-000-0000'
          });
        } else if (res.tapIndex === 2) {
          // 问题反馈
          wx.navigateTo({
            url: '/pages/feedback/feedback'
          });
        }
      }
    });
  },

  // 处理刷新
  handleRefresh: function () {
    wx.showLoading({
      title: '刷新中...'
    });

    // 重新获取数据
    this.fetchNotices();
    this.getUserData();
    this.getWeatherInfo();

    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    }, 800);
  },

  // 获取通知数据
  getNoticeData() {
    // 模拟获取通知数据
    // 实际项目中应该通过API请求获取
    const noticeList = [{
        id: 1,
        content: '学法减分题库拍照搜题以下内容您都试过了吗？'
      },
      {
        id: 2,
        content: '邀请好友使用可获得更多积分奖励！'
      }
    ];
    this.setData({
      noticeList
    });
  },
  handlePublic() {
    app.openShow({
      url: app.globalData.service_icon,
      title: '联系客服',
      from: 'home'
    })
  },
  closePopup() {
    this.setData({
      popupVisible: false
    })
  },
  // 任务中心
  handleTaskCenter() {
    wx.navigateTo({
      url: '/pages/task/task'
    });
  },

  // 车品商城
  handleCarMall() {
    wx.navigateTo({
      url: '/pages/mall/mall'
    });
  },

  // 新人指引
  handleGuide() {
    wx.navigateTo({
      url: '/pages/guide/guide'
    });
  },

  // 拍照识题
  handlePhotoSearch() {
    wx.switchTab({
      url: '/pages/photo/photo'
    });
  },

  // 认证商家
  handleMerchant() {
    wx.navigateTo({
      url: '/pages/merchant/merchant'
    });
  },

  // 车友福利
  handleBenefit() {
    wx.navigateTo({
      url: '/pages/benefit/benefit'
    });
  },

  // 驾考题库
  handleTravel() {
    wx.navigateTo({
      url: '/pages/exam/exam'
    });
  },

  // 保险电话
  handleInsurance() {
    wx.navigateTo({
      url: '/pages/insurance/insurance',
    })
  },

  // 加油站导航
  handleGasStation() {
    // wx.navigateTo({
    //   url: '/pages/gas-station/index',
    // })
    wx.navigateTo({
      url: '/pages/nav-map/index?title=' + '加油站',
    })
  },

  // 停车场查找
  handleParking() {
    wx.navigateTo({
      url: '/pages/nav-map/index?title=' + "停车场",
    })
  },
  // 停车场查找
  handleCarWash() {
    wx.navigateTo({
      url: '/pages/nav-map/index?title=' + "自助洗车",
    })
  },

  // 道路救援服务
  handleRoadRescue() {
    wx.navigateTo({
      url: '/pages/road-rescue/index',
    })
  },

  // 油耗计算器
  handleFuelCalculator() {
    wx.navigateTo({
      url: '/pages/fuel-calculator/index',
    })
  },

  // 二手车估值
  handleCarValuation() {
    wx.navigateTo({
      url: '/pages/car-valuation/index',
    })
  },

  // 车贷计算
  handleLoanCalculator() {
    wx.navigateTo({
      url: '/pages/loan-calculator/index',
    })
  },

  // DD代驾
  handleDDDriving() {
    // 显示DD代驾弹窗
    this.setData({
      showDDPopup: true
    });
  },

  // 关闭DD代驾弹窗
  closeDDPopup() {
    this.setData({
      showDDPopup: false
    });
  },

  // 处理分享
  handleShare() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 检查用户信息是否完整
  checkUserInfo: function () {
    return;
    const userInfo = app.globalData.userInfo || {};

    // 如果昵称是"微信用户"（默认值），则显示弹窗要求用户设置
    if (userInfo.nickName === "微信用户") {
      this.setData({
        showUserInfoPopup: true
      });
    }
  },

  // 用户信息保存处理
  handleUserInfoSave: function (e) {
    const {
      userInfo
    } = e.detail;
    const app = getApp();

    wx.showLoading({
      title: '保存中',
    });

    // 准备要更新的用户数据
    const updateData = {
      user_id: app.globalData.userInfo.user_id,
      nick_name: userInfo.nickName,
      avatar_url: userInfo.avatarUrl
    };

    request(api.updateProfile, 'POST', updateData)
      .then(res => {
        // 服务器更新成功，更新本地数据
        const newUserInfo = res.data.userInfo;

        // 更新全局数据
        if (app.globalData) {
          app.globalData.userInfo = newUserInfo;
        }

        // 更新本地存储
        wx.setStorage({
          key: 'userInfo',
          data: newUserInfo
        });

        this.setData({
          showUserInfoPopup: false
        });

        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
      })
      .catch(err => {
        // 服务器更新失败
        wx.hideLoading();
        wx.showToast({
          title: '保存失败，请重试',
          icon: 'none'
        });
        console.error('更新用户信息失败', err);
      });
  },

  // 处理公告点击
  handleAnnouncementTap() {
    wx.showModal({
      title: '使用须知',
      content: this.data.noticeText,
      showCancel: false,
      confirmText: '我知道了'
    });
  },

  onShowAd() {
    const userId = wx.getStorageSync('userId');
    rewardAd.showRewardAd();
  },

  unlockContent() {
    const userId = wx.getStorageSync('userId');
    request(api.videoAd + '?user_id=' + userId, 'GET')
      .then(res => {
        wx.showToast({
          title: '奖励已发放'
        });
      })
      .catch(err => {
        console.error('发放奖励失败', err);
      });
  }
})